<?php
/**
 * Created by PhpStorm.
 * User: lz
 * Date: 2017/8/17
 * Time: 19:04
 */

namespace app\common\service\weixin;


use app\common\components\HttpClient;
use app\common\service\BaseService;
use app\models\oauth\OauthAccessToken;

class RequestService extends BaseService
{
    private static $app_id = "";
    private static $app_secret = "";
    private static $app_token = "";

    private static $url = "https://api.weixin.qq.com/cgi-bin/";

    //获取token
    public static function getAccessToken()
    {
        $date_now = date("Y-m-d H:i:s");

        $access_token_info = OauthAccessToken::find()->where([">", "expired_time", $date_now])->limit(1)->one();

        if ($access_token_info) {
            return $access_token_info["access_token"];
        }

        //调用接口获取token
        $path = "token?grant_type=client_credential&appid=" . self::getAppId() . "&secret=" . self::$app_secret;

        $res = self::send($path);

        if (!$res) {
            return self::_err(self::getLastErrorMsg());
        }

        $model_access_token = new OauthAccessToken();

        $model_access_token->access_token = $res['access_token'];
        $model_access_token->expired_time = date("Y-m-d H:i:s", $res['expires_in'] + time() - 200);
        $model_access_token->created_time = $date_now;
        $model_access_token->save(0);

        return $res['access_token'];
    }

    //调用接口
    public static function send($path, $data = [], $method = "GET")
    {
        $request_url = self::$url . $path;

        if ($method == "GET") {
            $res = HttpClient::get($request_url, []);
        } else {
            $res = HttpClient::post($request_url, $data);
        }

        $rst = json_decode($res, true);

        if (!$rst || (isset($rst["errcode"]) && $rst["errcode"])) {
            return self::_err($rst["errmsg"]);
        }

        return $rst;
    }

    public static function set($app_id, $app_secret, $app_token)
    {
        self::$app_id = $app_id;
        self::$app_secret = $app_secret;
        self::$app_token = $app_token;
    }

    /**
     * @return string
     */
    public static function getAppId()
    {
        return self::$app_id;
    }

    /**
     * @return string
     */
    public static function getAppSecret()
    {
        return self::$app_secret;
    }

    /**
     * @return string
     */
    public static function getAppToken()
    {
        return self::$app_token;
    }

}

